package com.xuecheng.order.service;

import com.xuecheng.framework.domain.task.XcTask;
import com.xuecheng.framework.domain.task.XcTaskHis;
import com.xuecheng.order.dao.XcTaskHisRepository;
import com.xuecheng.order.dao.XcTaskRepository;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author zhaoxiang
 * @version 1.0
 * @Date 2020/2/26 18:19
 */
@Service
public class TaskService {

    @Autowired
    private XcTaskRepository xcTaskRepository;

    @Autowired
    private XcTaskHisRepository xcTaskHisRepository;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 取出前n条任务,取出指定时间之前处理的任务
     *
     * @param updateTime
     * @param size
     * @return
     */
    public List<XcTask> findTaskList(Date updateTime, int size){
        //设置分页参数
        Pageable pageable = new PageRequest(0,size);
        //查询前n条任务
        Page<XcTask> xcTasks = xcTaskRepository.findByUpdateTimeBefore(pageable,updateTime);
        List<XcTask> taskList = xcTasks.getContent();
        return taskList;
    }

    /**
     * 乐观锁方法校验任务
     *
     * @param id
     * @param version
     * @return
     */
    @Transactional
    public int getTask(String id, int version){
        int count = xcTaskRepository.updateTaskVersion(id, version);
        return count;
    }

    /**
     * 结束任务（删除任务）
     * @param taskId
     */
    @Transactional
    public void finishTask(String taskId){
        Optional<XcTask> taskOptional = xcTaskRepository.findById(taskId);
        if (taskOptional.isPresent()){
            XcTask xcTask = taskOptional.get();
            xcTask.setDeleteTime(new Date());
            XcTaskHis xcTaskHis = new XcTaskHis();
            BeanUtils.copyProperties(xcTask, xcTaskHis);
            xcTaskHisRepository.save(xcTaskHis);
            xcTaskRepository.delete(xcTask);
        }
    }

    /**
     * 发送消息
     *
     * @param xcTask 任务对象
     * @param ex   交换机id
     * @param routingKey
     */
    public void publish(XcTask xcTask,String ex,String routingKey){
        //查询任务
        Optional<XcTask> xcTaskOptional = xcTaskRepository.findById(xcTask.getId());
        if (xcTaskOptional.isPresent()){
            rabbitTemplate.convertAndSend(ex, routingKey, xcTask);
            //更新任务时间updateTime
            XcTask xcTask1 = xcTaskOptional.get();
            xcTask1.setUpdateTime(new Date());
            xcTaskRepository.save(xcTask1);
        }
    }
}
